﻿<%@ WebHandler Language="C#" Class="_order" %>

using System;
using System.Web;
using System.Data;
using System.Collections.Generic;
using System.Collections;
using NS.BLL.Systems;
using NS.Utilities;
using BLL;
using Model;
using WxPay;

public class _order : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        //取得处事类型
        string action = context.Request["ac"];

        switch (action)
        {
            case "list": //订单列表
                list(context);
                break;
            case "info": //订单信息
                info(context);
                break;
            case "emplist": //员工订单列表
                emplist(context);
                break;
            case "empinfo": //员工信息
                empinfo(context);
                break;
            case "submit": //提交订单
                submit(context);
                break;
            case "cancel": //取消订单
                cancel(context);
                break;
            case "empcancel": //员工取消订单
                empcancel(context);
                break;
            case "start": //开始洗车
                start(context);
                break;
            case "cmplete": //完成洗车
                cmplete(context);
                break;
            case "getWait": //获得排队信息
                getWait(context);
                break;

        }
    }

    private void getWait(HttpContext context)
    {
        string result = string.Empty;
        int userCount = UaerComService.GetUserCount();
        string[] WaitInfo = OrderService.GetWaitInfo(null);
        string count = WaitInfo[0];
        int times = int.Parse(WaitInfo[1]);
        if (userCount > 0)
        {
            times = times / userCount;
        }

        int swork = int.Parse(DictionaryService.GetDicValue("工作时间", "开始时间"));
        int ework = int.Parse(DictionaryService.GetDicValue("工作时间", "结束时间"));
        int now = DateTime.Now.Hour;
        int show = 0;
        DateTime startTime = DateTime.Now;
        if (now < swork)
        {
            startTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + swork + ":00:00");
        }
        else if (now > ework)
        {
            show = 1;
            startTime = DateTime.Parse(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + " " + swork + ":00:00");
        }
        startTime = startTime.AddMinutes(times);
        TimeSpan ts = Convert.ToDateTime(startTime.ToString("yyyy-MM-dd")).Subtract(Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")));
        string time = startTime.ToString("yyyy-MM-dd HH:mm:ss");
        if (ts.Days == 0)
        {
            time = "今天" + startTime.ToString("HH:mm");
        }
        else if (ts.Days == 1)
        {
            time = "明天" + startTime.ToString("HH:mm");
        }
        else if (ts.Days == 2)
        {
            time = "后天" + startTime.ToString("HH:mm");
        }
        result = "{count:'" + count + "',show:'" + show + "',time:'" + time + "'}";
        context.Response.Write(result);
    }
    private void info(HttpContext context)
    {
        string result = string.Empty;
        long resLong;
        long oid = long.TryParse(context.Request["oid"], out resLong) ? resLong : 0;
        Order Model = OrderService.GetOrderByOrderID(oid);
        if (Model != null)
        {
            Model.StateName = DictionaryService.GetDicName("订单状态", Model.State.ToString());
        }
        result = JsonHelper.T2JSON(Model);
        context.Response.Write(result);
    }

    private void cancel(HttpContext context)
    {
        string id = context.Request["id"];
        string couponsid = context.Request["couponsid"];
        string result = OrderService.Cancel(id);
        if (!string.IsNullOrEmpty(result))
        {
            result = JsonMessager.Fail(result);
        }
        else
        {
            result = JsonMessager.Success("取消成功");
        }
        context.Response.Write(result);
    }
    private void empcancel(HttpContext context)
    {
        string id = context.Request["id"];
        string couponsid = context.Request["couponsid"];
        string result = OrderService.EmpCancel(id);
        if (!string.IsNullOrEmpty(result))
        {
            result = JsonMessager.Fail(result);
        }
        else
        {
            result = JsonMessager.Success("取消成功");
        }
        context.Response.Write(result);
    }

    private void start(HttpContext context)
    {
        string id = context.Request["id"];
        string result = OrderService.Start(id);
        if (!string.IsNullOrEmpty(result))
        {
            result = JsonMessager.Fail(result);
        }
        else
        {
            result = JsonMessager.Success("操作成功");
        }
        context.Response.Write(result);
    }
    private void cmplete(HttpContext context)
    {
        string id = context.Request["id"];
        string result = OrderService.Cmplete(id);
        if (!string.IsNullOrEmpty(result))
        {
            result = JsonMessager.Fail(result);
        }
        else
        {
            result = JsonMessager.Success("操作成功");
        }
        context.Response.Write(result);
    }

    private void submit(HttpContext context)
    {
        string result = string.Empty;
        bool ispay = false;
        int orderid = 0;
        try
        {
            int resInt;
            decimal resDecimal;
            decimal cash = decimal.TryParse(context.Request["cash"], out resDecimal) ? resDecimal : 0;
            decimal blance = MemberAccountService.GetBlance(CookieHelper.GetValue("openid"));
            int CouponsID = int.TryParse(context.Request["cpid"], out resInt) ? resInt : 0;
            if (string.IsNullOrEmpty(CookieHelper.GetValue("openid")))
            {
                result = "登陆超时";
            }
            else if (cash > 0 && cash > blance)
            {
                result = "账户余额不足";
            }
            else if (CouponsService.IsUse(CouponsID))
            {
                result = "洗车券无效";
            }
            else
            {
                Order Model = new Order();
                Model.OpenID = CookieHelper.GetValue("openid");
                Model.OrderNo = string.Format("{0}{1}", DateTime.Now.ToFileTimeUtc().ToString(), new Random().Next(99));
                Member m = MemberService.GetMemberByOpenID(CookieHelper.GetValue("openid"));
                if (m != null)
                {
                    Model.TrueName = m.TrueName + (!string.IsNullOrEmpty(m.Sex) ? "(" + m.Sex + ")" : "");
                    Model.Mobile = m.Mobile;
                }
                Model.CarID = int.Parse(context.Request["carid"]);
                Model.CarNumber = context.Request["carnmber"];
                Model.CarType = context.Request["cartype"];

                Model.Address = context.Request["address"];
                Model.Lat = context.Request["lat"];
                Model.Lng = context.Request["lng"];

                Model.Interior = int.TryParse(context.Request["inter"], out resInt) ? resInt : 0;
                Model.Price = decimal.Parse(context.Request["price"]);
                Model.Times = int.Parse(context.Request["times"]);

                Model.CouponsID = CouponsID;
                Model.CouType = int.TryParse(context.Request["cptype"], out resInt) ? resInt : 0;


                Model.Memo = context.Request["memo"];
                Model.AddDate = DateTime.Now;
                if (Model.CouType == 0)
                {
                    Model.CouponsMoney = decimal.TryParse(context.Request["cpmoney"], out resDecimal) ? resDecimal : 0;
                    Model.Cash = cash;
                    Model.Pay = Model.Price - Model.CouponsMoney - Model.Cash;
                    if (Model.Pay > 0)
                    {
                        Model.State = 0;
                        ispay = true;
                    }
                    else
                    {
                        Model.State = 1;
                        Model.PayDate = DateTime.Now;
                    }
                }
                else
                {
                    Model.CouponsMoney = 0;
                    Model.Cash = 0;
                    Model.Pay = 0;
                    Model.PayDate = DateTime.Now;
                    Model.State = 1;
                }
                orderid = OrderService.AddOrder(Model);
                if (orderid > 0)
                {
                    ArrayList sqlList = new ArrayList();
                    if (Model.CouponsID > 0)
                    {
                        sqlList.Add(CouponsService.UpdateUse_SQL(Model.CouponsID.Value, 1));
                    }
                    if (Model.Cash > 0)
                    {
                        MemberAccount ma = new MemberAccount();
                        ma.OpenID = Model.OpenID;
                        ma.OpType = BLL.EnumHelper.AccountType.消费.ToString();
                        ma.Money = -Model.Cash.Value;
                        ma.TradeID = Model.OrderNo;
                        ma.Date = DateTime.Now;
                        sqlList.Add(MemberAccountService.AddMemberAccount_SQL(ma));
                    }
                    if (sqlList.Count > 0)
                    {
                        if (!OrderService.TransUpdate(sqlList))
                        {
                            OrderService.DeleteOrderByOrderID(orderid);
                            result = JsonMessager.Fail("提交失败");
                        }
                    }
                }
                else
                {
                    result = "提交失败！";
                }
            }
        }
        catch (Exception ex)
        {
            Log.Error(this.GetType().ToString(), "订单提交失败：" + ex.ToString()
            + "；carid：" + context.Request["carid"]
            + "；cartype：" + context.Request["cartype"]
            + "；carnmber：" + context.Request["carnmber"]
            + "；address：" + context.Request["address"]
            + "；lat：" + context.Request["lat"]
            + "；lng：" + context.Request["lng"]
            + "；inter：" + context.Request["inter"]
            + "；price：" + context.Request["price"]
            + "；protimes：" + context.Request["protimes"]
            + "；cpid：" + context.Request["cpid"]
            + "；cptype：" + context.Request["cptype"]
            + "；cpmoney：" + context.Request["cpmoney"]
            + "；memo：" + context.Request["memo"]
            + "；paymoney：" + context.Request["paymoney"]);
            result = "提交失败！";
        }
        if (string.IsNullOrEmpty(result))
        {
            if (ispay)
            {
                result = JsonMessager.Success(orderid);
            }
            else
            {
                result = JsonMessager.Success(0);
            }
        }
        else
        {
            result = JsonMessager.Fail(result);
        }
        context.Response.Write(result);
    }

    private void list(HttpContext context)
    {
        string result = string.Empty;
        string state = context.Request["state"];
        List<Order> list = OrderService.GetAllOrder(CookieHelper.GetValue("openid"), state);
        foreach (Order Model in list)
        {
            Model.StateName = DictionaryService.GetDicName("订单状态", Model.State.ToString());

            if (Model.State.Value == 0 || Model.State.Value == 1)
            {
                string PayDate = string.Empty;
                if (Model.PayDate != null)
                {
                    PayDate = Model.PayDate.ToString();
                }
                int userCount = UaerComService.GetUserCount();
                string[] WaitInfo = OrderService.GetWaitInfo(PayDate);
                string count = WaitInfo[0];
                int times = int.Parse(WaitInfo[1]);
                if (userCount > 0)
                {
                    times = times / userCount;
                }
                int swork = int.Parse(DictionaryService.GetDicValue("工作时间", "开始时间"));
                int ework = int.Parse(DictionaryService.GetDicValue("工作时间", "结束时间"));
                int now = DateTime.Now.Hour;
                DateTime startTime = DateTime.Now;
                if (now < swork)
                {
                    startTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + swork + ":00:00");
                }
                else if (now > ework)
                {
                    startTime = DateTime.Parse(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + " " + swork + ":00:00");
                }
                startTime = startTime.AddMinutes(times);
                TimeSpan ts = Convert.ToDateTime(startTime.ToString("yyyy-MM-dd")).Subtract(Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")));
                string time = startTime.ToString("yyyy-MM-dd HH:mm:ss");
                if (ts.Days == 0)
                {
                    time = "今天" + startTime.ToString("HH:mm");
                }
                else if (ts.Days == 1)
                {
                    time = "明天" + startTime.ToString("HH:mm");
                }
                else if (ts.Days == 2)
                {
                    time = "后天" + startTime.ToString("HH:mm");
                }
                Model.WaitTip = "有 " + count + " 人排队<br />预计开始时间：" + time;
            }
        }
        result = JsonHelper.T2JSON(list);
        context.Response.Write(result);
    }

    private void empinfo(HttpContext context)
    {
        string result = string.Empty;
        string openid = CookieHelper.GetValue("openid");
        string userid = UserService.GetUserID(openid);
        string name = UserService.GetTrueName(openid);
        result = "{userid:'" + userid + "',name:'" + name + "'}";
        context.Response.Write(result);
    }

    private void emplist(HttpContext context)
    {
        string result = string.Empty;
        string state = context.Request["state"];
        List<Order> list = OrderService.GetEmpOrder(state, CookieHelper.GetValue("openid"));
        foreach (Order Model in list)
        {
            Model.CarColor = MemberCarService.GetColor(Model.CarID.Value);
            Model.StateName = DictionaryService.GetDicName("订单状态", Model.State.ToString());
        }
        result = JsonHelper.T2JSON(list);
        context.Response.Write(result);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}